from fastapi import Cookie, HTTPException, APIRouter, Depends, Response, status, Security
from fastapi.security import SecurityScopes


router = APIRouter()


ALL_USERS = {
    'jack': ['admin', 'users', 'visitors'],
    'rose': ['users', 'visitors'],
    'tom': ['visitors']
}

ROLE_PERMISSION = {
    'admin': ['upload', 'download', 'visit'],
    'users': ['download', 'visit'],
    'visitors': ['visit']
}


# @router.get("/login")
# def set_cookie(resp: Response, username: str):
#     resp.set_cookie(key="username", value=username, expires=600)
#     return {"message": "cookie set"}


def get_user_token(username: str | None):
    if not username:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="user name required",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return username


def get_role_permissions(role_list: list[str]):
    permissions = []
    for role in role_list:
        permissions.extend(ROLE_PERMISSION[role])
    return permissions


def get_user_permissions(token: str = Depends(get_user_token)):
    if token not in ALL_USERS:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="user not found",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return get_role_permissions(ALL_USERS[token])


def check_user(security_scopes: SecurityScopes, user_permissions: str = Depends(get_user_permissions)):
    if not any(p in security_scopes.scopes for p in user_permissions):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not enough permissions",
            headers={"WWW-Authenticate": "Bearer"},
        )
